<template>
  <view class="container">
    <!-- 加载状态提示 -->
    <view v-if="loading" class="loading">
      <uni-icons type="spinner-cycle" size="30" color="#999"></uni-icons>
      <text>正在加载工单...</text>
    </view>
	

    <!-- 下拉刷新容器 -->
    <scroll-view 
      scroll-y 
      class="scroll-view"
      @refresherrefresh="handleRefresh"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
    >
      <!-- 工单列表 -->
      <view 
        v-for="item in orders" 
        :key="item.taskId" 
        class="order-card"
        @click="handleViewDetail(item.taskId)"
      >
        <view class="order-header">
          <!-- 显示工单编码 -->
          <text class="order-title">{{ item.taskCode || '未编码工单' }}</text>
          
          <view :class="['status-badge', statusClass(item.taskStatus)]">
            {{ formatStatus(item.taskStatus) }}
          </view>
        </view>
        
        <view class="order-meta">
          <text class="create-time">创建时间：{{ formatTime(item.createTime) }}</text>
          <!-- 显示数据库中的user_name字段 -->
          <text class="assignee">负责人：{{ item.userName || '未分配' }}</text>
        </view>

       <!-- 工单卡片内新增以下代码 -->
       <view class="action-buttons">
         <!-- 状态为 1（待办）时显示“开始”按钮 -->
         <button 
           v-if="item.taskStatus === 1"
           class="start-button"
           @click.stop="handleStart(item.taskId)"
         >
           开始
         </button>
       
         <!-- 状态为 2（进行中）时显示“完成”按钮 -->
         <button 
           v-if="item.taskStatus === 2"
           class="complete-button"
           @click.stop="handleCompleteConfirm(item.taskId)"
         >
           完成
         </button>
       </view>
      </view>
	  

      <!-- 空状态提示 -->
      <view v-if="!loading && orders.length === 0" class="empty-state">
        <uni-icons type="info" size="50" color="#999"></uni-icons>
        <text class="empty-text">当前没有待处理的工单</text>
      </view>
    </scroll-view>
	<!-- 分页控件 -->
	    <view class="pagination">
	      <button :disabled="pageNum === 1" @click="prevPage">上一页</button>
	      <text>{{ pageNum }} / {{ totalPage }}</text>
	      <button :disabled="pageNum >= totalPage" @click="nextPage">下一页</button>
	    </view>

  </view>
</template>

<script>
import { 
  listTask,
  updateTask,
  getTaskDetails, 
  updateTaskStatus,
  getTasksByEmpId
} from '@/api/task'

export default {
  data() {
    return {
      orders: [],        // 工单列表数据
      loading: true,     // 加载状态标识
      isRefreshing: false, // 下拉刷新状态标识
      queryParams: {     // 查询参数
        pageNum: 1,
        pageSize: 10 // 设置每页显示5条记录
      },
      totalPage: 1, // 总页数
      pageNum: 1 // 当前页码
    }
  },

  onLoad(options) {
    console.log('接收到的参数:', options)
  
    // 优先从 URL 参数获取 empId，否则从本地缓存读取
    let empId = options.empId || uni.getStorageSync('empId');
  
    if (empId) {
      // 尝试将 empId 转换为整数
      const parsedEmpId = parseInt(empId, 10);
    
      // 判断是否是一个合法的数字（排除 NaN）
      if (!isNaN(parsedEmpId)) {
        this.empId = parsedEmpId;
        uni.setStorageSync('currentEmpId', this.empId); // 缓存当前使用的 empId
        this.loadOrders(this.empId);
      } else {
        uni.showToast({
          title: 'empId 不是有效数字',
          icon: 'none'
        });
      }
    } else {
      uni.showToast({
        title: '无此员工',
        icon: 'none'
      });
    }
  },

  methods: {
    // 加载工单数据
    async loadOrders(empId) {
      try {
        const res = await getTasksByEmpId(empId)
        this.orders = res || []
      } catch (e) {
        uni.showToast({ title: '加载失败', icon: 'none' })
        console.error('加载工单失败:', e)
      } finally {
        this.loading = false
        this.isRefreshing = false
      }
    },

    // 处理下拉刷新
    async handleRefresh() {
      this.isRefreshing = true;
      this.queryParams.pageNum = 1;
      await this.loadOrders();
    },

   prevPage() {
     if (this.pageNum > 1) {
       this.pageNum--;
       this.queryParams.pageNum = this.pageNum;
       this.loadOrders(this.empId);
     }
   },
   
   nextPage() {
     if (this.pageNum < this.totalPage) {
       this.pageNum++;
       this.queryParams.pageNum = this.pageNum;
       this.loadOrders(this.empId);
     }
   },


    // 处理下拉刷新
    async handleRefresh() {
      this.isRefreshing = true
      this.queryParams.pageNum = 1
      await this.loadOrders()
    },

    // 处理完成操作
    async handleComplete(taskId) {
      try {
        const res = await updateTask({
          taskId: taskId,
          taskStatus: 3
        })
        
        if (res.code === 200) {
          uni.showToast({
            title: '状态更新成功',
            icon: 'success'
          })
          // 本地更新数据状态
          this.orders = this.orders.map(item => 
            item.taskId === taskId ? { ...item, taskStatus: 3 } : item
          )
        } else {
          throw new Error(res.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新失败:', error)
        uni.showToast({
          title: error.message || '更新失败，请重试',
          icon: 'none'
        })
      }
    },
	// 处理开始按钮
	async handleStart(taskId) {
	  const item = this.orders.find(order => order.taskId === taskId);
	  if (!item || !item.userId || isNaN(Number(item.userId))) {
	    throw new Error('无法获取负责人ID或ID无效');
	  }
	
	  try {
	    const res = await updateTaskStatus(Number(item.userId), Number(taskId));
	
	    if (res.code === 200) {
	      uni.showToast({ title: '已开始任务', icon: 'success' });
	      this.orders = this.orders.map(order =>
	        order.taskId === taskId ? { ...order, taskStatus: 2 } : order
	      );
	    } else {
	      throw new Error(res.msg || '操作失败');
	    }
	  } catch (error) {
	    uni.showToast({
	      title: error.message || '操作失败，请重试',
	      icon: 'none'
	    });
	  }
	},

    // 查看工单详情
    async handleViewDetail(taskId) {
      try {
        const res = await getTaskDetails(taskId)
        if (res.code === 200) {
          uni.navigateTo({
            url: `/pages/orderDetail/orderDetail?taskId=${taskId}`
          })
        } else {
          throw new Error(res.msg || '获取详情失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '获取详情失败',
          icon: 'none'
        })
      }
    },
	// 处理完成按钮的确认提示
	async handleCompleteConfirm(taskId) {
	  uni.showModal({
	    title: '提示',
	    content: '确定要标记为已完成吗？',
	    success: async (res) => {
	      if (res.confirm) {
	        const item = this.orders.find(order => order.taskId === taskId);
	        if (!item || !item.userId || isNaN(Number(item.userId))) {
	          uni.showToast({
	            title: '无法获取负责人ID或ID无效',
	            icon: 'none'
	          });
	          return;
	        }
	
	        try {
	          const response = await updateTaskStatus(Number(item.userId), Number(item.taskId));
	
	          if (response.code === 200) {
	            uni.showToast({ title: '任务已完成', icon: 'success' });
	            this.orders = this.orders.map(order =>
	              order.taskId === taskId ? { ...order, taskStatus: 4 } : order
	            );
	          } else {
	            throw new Error(response.msg || '操作失败');
	          }
	        } catch (error) {
	          uni.showToast({
	            title: error.message || '操作失败，请重试',
	            icon: 'none'
	          });
	        }
	      }
	    }
	  });
	},

    // 状态样式映射
    statusClass(status) {
      const statusMap = {
        1: 'pending',    // 待处理
        2: 'processing', // 进行中
        3: 'completed',  // 已完成
        4: 'urgent'      // 紧急
      }
      return statusMap[status] || 'default'
    },

    // 状态文本格式化
    formatStatus(status) {
      const statusTextMap = {
        1: '待办',
        2: '进行',
        3: '取消',
        4: '完成'
      }
      return statusTextMap[status] || '未知状态'
    },

    // 时间格式化
    formatTime(timestamp) {
      if (!timestamp) return '未知时间'
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
/* 容器样式 */
.container {
  padding: 20rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

/* 滚动视图样式 */
.scroll-view {
  height: calc(100vh - 40rpx);
}

/* 加载状态样式 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  
  text {
    color: #666;
    margin-top: 20rpx;
  }
}

/* 工单卡片样式 */
.order-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.08);

  /* 工单头部样式 */
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;

    /* 工单标题样式（编码显示） */
    .order-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 400rpx;
    }

    /* 状态标签样式 */
    .status-badge {
      padding: 6rpx 20rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
      margin-left: 20rpx;

      /* 不同状态样式 */
      &.pending { background: #fff7e6; color: #faad14; }
      &.processing { background: #e8f4ff; color: #1890ff; }
      &.completed { background: #e6ffed; color: #52c41a; }
      &.urgent { background: #fff2e8; color: #fa541c; }
      &.default { background: #f5f5f5; color: #666; }
    }
  }

  /* 工单元数据样式 */
  .order-meta {
    display: flex;
    justify-content: space-between;
    font-size: 26rpx;
    color: #666;
    margin-bottom: 24rpx;

    /* 负责人样式（添加截断） */
    .assignee {
      max-width: 240rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  /* 操作按钮组样式 */
  .action-buttons {
     display: flex;
     justify-content: flex-end; // 靠右对齐
     margin-top: 20rpx;

    /* 完成按钮样式 */
    .complete-button {
      background: #4CAF50;
      color: #fff;
      font-size: 28rpx;
      padding: 12rpx 32rpx;
      border-radius: 8rpx;
      line-height: 2.5;
      
      &::after { border: none; }
    }
  }
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 100rpx 0;
  
  .empty-text {
    display: block;
    color: #999;
    margin-top: 20rpx;
  }
}
.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;

  .start-button {
    background-color: #1890ff;
    color: white;
    font-size: 28rpx;
    padding: 12rpx 32rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
    &::after { border: none; }
  }

  .complete-button {
    background-color: #52c41a;
    color: white;
    font-size: 28rpx;
    padding: 12rpx 32rpx;
    border-radius: 30rpx;
	margin-right: 20rpx;
    &::after { border: none; }
  }
}
/* 添加分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;

  button {
    background-color: #1890ff;
    color: white;
    font-size: 28rpx;
    padding: 12rpx 32rpx;
    border-radius: 8rpx;
    &::after { border: none; }
    &:disabled {
      background-color: #cccccc;
    }
  }

  text {
    font-size: 28rpx;
  }
}

</style>